package com.uduemc.biso.node.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.utils.CryptoJava;
import com.uduemc.biso.node.core.entities.SComponent;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.exception.NotFound404Exception;
import com.uduemc.biso.node.web.service.byfeign.ComponentService;

@Controller
public class PrivateMapController {

	@Autowired
	private ComponentService componentServiceImpl;

	@Autowired
	private RequestHolder requestHolder;

	@GetMapping({ "/private/map/baidu.html", "/site/*/private/map/baidu.html" })
	public String mapbaidu(@RequestParam("unique") String unique, HttpServletResponse response)
			throws NotFound404Exception, JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (StringUtils.isEmpty(unique)) {
			throw new NotFound404Exception("未能获取到 unique 参数！");
		}
		int id = 0;
		try {
			String idString = CryptoJava.de(unique);
			id = Integer.valueOf(idString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (id < 1) {
			throw new NotFound404Exception("获取到 unique 参数转成 id 失败！");
		}

		// 组件数据是否存在
		long hostId = requestHolder.getHostId();
		SComponent sComponent = componentServiceImpl.getInfoByHostIdAndId(hostId, id);
		if (sComponent == null) {
			throw new NotFound404Exception("未能获取到 sComponent 数据！");
		}
		return "private/map/baidu";
	}

	@GetMapping({ "/private/map/google.html", "/site/*/private/map/google.html" })
	public String mapgoogle(@RequestParam("unique") String unique, HttpServletResponse response)
			throws NotFound404Exception, JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (StringUtils.isEmpty(unique)) {
			throw new NotFound404Exception("未能获取到 unique 参数！");
		}
		int id = 0;
		try {
			String idString = CryptoJava.de(unique);
			id = Integer.valueOf(idString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (id < 1) {
			throw new NotFound404Exception("获取到 unique 参数转成 id 失败！");
		}

		// 组件数据是否存在
		long hostId = requestHolder.getHostId();
		SComponent sComponent = componentServiceImpl.getInfoByHostIdAndId(hostId, id);
		if (sComponent == null) {
			throw new NotFound404Exception("未能获取到 sComponent 数据！");
		}
		return "private/map/google";
	}
}
